#!/usr/bin/env bash

readonly script=otomi
readonly current_branch=$(git rev-parse --abbrev-ref HEAD)
readonly branch=${OTOMI_TAG:-$current_branch}
readonly remote=https://raw.githubusercontent.com/linode/apl-core/$branch/binzx/$script
readonly path=/usr/local/bin

readonly msg="Please choose the default install location [$path]: "

# https://unix.stackexchange.com/questions/121231/how-to-read-user-input-from-a-pipe
read -p "$msg" answer <&2
answer=${answer:-$path}

if [ ! -d $answer ]; then
  echo "$answer does not exist, please provide an existing path"
  exit 1
fi

if [[ $PATH != *$answer* ]]; then
  echo "$answer is not in your PATH please add it to run $script from anywhere"
  echo "export PATH=$answer:\$PATH"
fi

file="$answer/$script"
if command -v wget &>/dev/null; then
  wget $remote -O $file
elif command -v curl &>/dev/null; then
  curl $remote -o $file
fi
chmod +x $file

if [[ $SHELL == *zsh* ]] || [[ $SHELL == *bash* ]]; then
  readonly msgAC="Do you want to install autocompletion for otomi? [Yes/no]: "
  read -p "$msgAC" autocompleteAnswer <&2
  autocompleteAnswer=${autocompleteAnswer:-yes}
  case $autocompleteAnswer in
    [Yy]*)
      acPath='/usr/local/share/zsh/site-functions/_otomi'
      if [[ $SHELL == *bash* ]]; then
        acPath='/usr/local/etc/bash_completion.d/otomi.bash'
        mkdir -p /usr/local/etc/bash_completion.d
      else
        mkdir -p /usr/local/share/zsh/site-functions
      fi
      otomi completion | tr -d '\r' >$acPath
      chmod +x $acPath
      echo "Autocompletion has been installed in ${acPath}"
      echo "Please restart your terminal to use autocompletion"
      ;;
    [Nn]*)
      echo "If you need autocompletion you can run:"
      echo "\`otomi completion\`"
      ;;
  esac
fi

# The /tmp/otomi is created by regular user. Installer creates it with root permisions only
rm -rf /tmp/otomi

echo "Otomi has been installed in $file"
echo 'You can now run it by calling `otomi`'
